const _ = require('lodash');
const verifyFacade = require('./../facade/verify.server.facade.js');
const request = require('request');  
const socket = require('socket.io');  
module.exports = {
    addVerify : addVerify,
    getVerifyById : getVerifyById,
    getVerifyByMid : getVerifyByMid,
    getAllVerify : getAllVerify,
    modifyVerifyState : modifyVerifyState,
    modifyVerifyBlock : modifyVerifyBlock
}

function addVerify(req,res,next) {
    let merchant = req.body;
    
    verifyFacade.addVerify(merchant, (error,result)=>{
        if(error) return next(error,req,res);
        return res.json(result);   
    });
}

function getVerifyById(req,res,next) {
    let id = req.params.id;
    verifyFacade.getVerifyById(id, (error,result)=>{
        if(error) return next(error,req,res);
        return res.json(result);   
    });
}

function getVerifyByMid(req,res,next){
    let mid = req.params.mid;

    verifyFacade.getVerifyByMid(mid, (error,result)=>{
        if(error) return next(error,req,res);
        return res.json(result);   
    });
}

function getAllVerify(req,res,next){
    let state = req.params.state;
    let block = req.params.block;
    
    verifyFacade.getAllVerify(state, block, (error,result)=>{
        if(error) return next(error,req,res);

        return res.json(result);   
    });
}

function modifyVerifyState(req,res,next){
    let id = req.body.id;
    let state = req.body.state;
    let msg = req.body.msg;
    verifyFacade.getVerifyById(id, (error,v)=>{
        if(error) return next(error,req,res);
        if(v){
            v.state = state;
            v.verifyTime = new Date();
            v.msg = msg;
            verifyFacade.updateVerify(v, (error, result)=>{
                if(error) return next(error,req,res);
                post("http://10.222.29.189:8888/meat/api/merchant/updateByAdmin",{mid:v.mid, state:v.state, block:v.block},function(error, response, body){});
                return res.json(result);
            });
        }
    });
}

function modifyVerifyBlock(req,res,next){

    let id = req.body.id;
    let block = req.body.block;
    verifyFacade.getVerifyById(id, (error,v)=>{
        if(error) return next(error,req,res);
        if(v){
            v.block = block;
            verifyFacade.updateVerify(v, (error, result)=>{
                if(error) return next(error,req,res);
                post("http://10.222.29.189:8888/meat/api/merchant/updateByAdmin",{mid:v.mid, state:v.state, block:v.block},function(error, response, body){});
                return res.json(result);
            });
        }
    });
}

function post(url, body, callback){
    request({
        url: url,
        method: "POST",
        json: true,
        body: body
    }, callback); 
}